package com.nage.components.movement;

import android.util.Log;

import com.nage.components.collision.Collidable;
import com.nage.components.collision.Collision;
import com.nage.components.collision.CollisionManager;
import com.nage.components.collision.CollisionMask;
import com.nage.components.collision.PongBat;
import com.nage.engine.GameGraphException;
import com.nage.engine.GameObject;
import com.nage.input.Input;
import com.nage.input.InputResponder;
import com.nage.input.InputSystem;

public class PongBall extends Collidable implements InputResponder {

	private byte m_State;
	private int m_p1Score; // scores for each player
	private int m_p2Score;
	private int m_GameCount;
	
	private static final byte RESET = 0x01; // Ball is not moving and reset to centre of game.
	private static final byte IN_PLAY = 0x02; // Ball is in play, bouncing around and stuff.

	public PongBall(GameObject p) {
		super(p);
		id = PONG_BALL;
		m_State = RESET;
		m_p1Score = 0;
		m_p2Score = 0;
		m_GameCount = 0;
		InputSystem.registerResponder(this);
	}
	
	@Override
	public boolean findLinks() throws GameGraphException {
		if(!super.findLinks()) {
			return false;
		}
		resetGame();
		return true;
	}
	
	@Override
	public void update(long delta) {
		switch(m_State) {
		case IN_PLAY:
			// Check for wall bounce.
			if(parent.x < 0 || parent.x > 1) {
				m_Physics.vel.x *= -1;
				m_Physics.acc.x *= -1;
			}
			// Check for off screen
			if(parent.y > 1) {
				m_p1Score++; 
				resetGame();
			} else if (parent.y < 0) {
				m_p2Score++;
				resetGame();
			}
			break;
		}
		
	}
	
	private void resetGame() {
		m_Physics.stop();
		m_Physics.dragCoef = 0.0f;
		parent.x = 0.5f;
		parent.y = 0.5f;
		m_State = RESET;
		Log.i("PongBall", "Player 1 ::  "+m_p1Score+" - "+m_p2Score+"  :: Player 2");
	}

	private void startGame() {
		switch (m_GameCount++ % 4) {
		case 0:
			m_Physics.addImpulse(5, 5);
			break;
		case 1:
			m_Physics.addImpulse(-5, 5);
			break;
		case 2:
			m_Physics.addImpulse(5, -5);
			break;
		case 3:
			m_Physics.addImpulse(-5, -5);
			break;
		}
		m_State = IN_PLAY;
	}

	@Override
	public void onCollision(Collision c) {
		Log.d("PongBall", "onCollision");
		collisions++;
		m_Physics.vel.y *= -1.1;
		m_Physics.acc.y *= -1;
		m_Physics.vel.x += (1 * ((PongBat) c.getOtherCollidable(this)).getXModifier());
	}

	@Override
	public void onInputEvent(Input i) {
		if(m_State == RESET && 
				i.x > 0.3 && i.x < 0.7 && i.y > 0.3 && i.y < 0.7)
			startGame();		
	}
	
	@Override
	public byte getOwner() {
		return parent.m_Owner;
	}

}
